import { defineStore } from 'pinia'
import { getUUID } from '@/assets/utils'
import { create2DArray } from '@/components/VTable/utils'
import type { VTableForm } from '@/components/VTable/types'

export const useTableStore = defineStore('table', {
  state: () => ({
    arr: [] as any[],
    currentId: ''
  }),
  getters: {
    currentTables: (state) => {
      return state.arr.find((el) => el.id === state.currentId)?.tables
    },
    currentForms: (state) => {
      return state.arr.find((el) => el.id === state.currentId)?.forms
    },
    getFormByTdId: (state) => {
      return (tdId: string) =>
        state.arr
          .find((el) => el.id === state.currentId)
          ?.forms.find((form: any) => form.tdId === tdId)
    }
  },
  actions: {
    changeTable(tableId: string) {
      this.currentId = tableId
    },
    // 创建表格
    createTable() {
      const row = 4
      const col = 4
      const obj: VTableForm = {
        id: 'table-' + getUUID(),
        forms: [],
        tables: create2DArray(row, col, {
          w: 1,
          h: 1
        }),
        tableAttr: {
          title: '表格名称',
          bgColor: '#ffffff',
          borderColor: '#eeeeee'
        }
      }
      this.arr.push(obj)
      this.currentId = obj.id
    },
    // 更新表格
    updateTables(tables: any): void {
      this.arr = this.arr.map((el: any) => {
        if (el.id === this.currentId) {
          el.tables = tables
        }
        return el
      })
    },
    // 添加表单项
    addFormItem(tdId: string, formType: string) {
      this.arr = this.arr.map((el: any) => {
        if (el.id === this.currentId) {
          el.forms.push({
            id: 'input-' + getUUID(),
            tdId,
            formType
          })
        }
        return el
      })
    },
    // 更新表单项
    updateFormItem(tableId: string, inputId: string, formConfig: any) {
      this.arr = this.arr.map((el: any) => {
        if (el.id === tableId) {
          el.forms = el.forms.map((form: any) => {
            if (form.id === inputId) {
              form = formConfig
            }
            return el
          })
        }
        return el
      })
    },
    // 移除表单项
    removeFormItem(tableId: string, inputId: string) {
      this.arr = this.arr.map((el: any) => {
        if (el.id === tableId) {
          el.forms = el.forms.filter((form: any) => {
            return form.id != inputId
          })
        }
        return el
      })
    },
    persist: true
  }
})
